﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using FSViet.Survey.Helpers;
using log4net;

namespace FSViet.Survey
{
	public partial class VKHTCNNSurvey : System.Web.UI.Page
	{
		ILog _logger = LogManager.GetLogger("RollingFile");
		protected void Page_Load(object sender, EventArgs e)
		{
			_logger.InfoFormat("VKHTCNN Survey page: Request URL: {0}; RefUrl: {1}", Request.Url, Request.UrlReferrer);
			if (Request.QueryString["SiteId"] == null 
				|| Request.QueryString["CampaignId"] == null
				|| Request.QueryString["Hash"] == null
				|| Request.QueryString["Sign"] == null)
				Response.Redirect("~/Error.aspx?msg=Invalid request");
			else
			{
				var key = HttpRuntime.Cache[Request.QueryString["Sign"]];
				if (key == null)
					Response.Redirect("~/Error.aspx?msg=Invalid request. Not found key");

				//validate request
				var hash = Security.EncryptPassword(Request.QueryString["SiteId"] + "-" + Request.QueryString["CampaignId"] + "-" + key.ToString());
				if (hash!=Request.QueryString["Hash"])
					Response.Redirect("~/Error.aspx?msg=Invalid request. Invalid hash");
			}
		}

		protected void SurveyButton_Click(object sender, EventArgs e)
		{
			if (!IsValidInput()) return;
			DataHelper dataH = new DataHelper();
			try
			{
				int qualification = 0;
				if (IntermediateCheck.Checked)
					qualification = 1;
				else if (UniversityCheck.Checked)
					qualification = 2;
				else if (GraduateCheck.Checked)
					qualification = 3;

				string userId = GlobalApplication.GetGuidS(Guid.NewGuid());
				dataH.Execute("INSERT INTO VKHTCNN_UserInfo(Id, Age, Gender, LevelOfEducation, Qualification, Component, SiteId, CampaignId, Created) VALUES(@Id, @Age, @Gender, @LevelOfEducation, @Qualification, @Component, @SiteId, @CampaignId, @Created)",
					dataH.CreateParam("Id", SqlDbType.Char, userId),
					dataH.CreateParam("Age", SqlDbType.Int, Convert.ToInt32(AgeInput.Text)),
					dataH.CreateParam("Gender", SqlDbType.Char, ManCheck.Checked ? 0 : 1),
					dataH.CreateParam("LevelOfEducation", SqlDbType.NVarChar, LevelOfEducationInput.Text.Trim()),
					dataH.CreateParam("Qualification", SqlDbType.Int, qualification),
					dataH.CreateParam("Component", SqlDbType.Char, PeopleCheck.Checked ? 0 : 1),
					dataH.CreateParam("SiteId", SqlDbType.Char, Request.QueryString["SiteId"]),
					dataH.CreateParam("CampaignId", SqlDbType.Char, Request.QueryString["CampaignId"]),
					dataH.CreateParam("Created", SqlDbType.DateTime, DateTime.Now));

				//Session["UserId"] = userId;
				//Response.Redirect("~/Survey.aspx");
				Page.RegisterClientScriptBlock("StartSurvey",
							string.Format("<script>document.location.href='Survey.aspx?SiteId={0}&CampaignId={1}&UserId={2}&Hash={3}&Sign={4}&TotalQuestionOnPage={5}'</script>",
							Request.QueryString["SiteId"],
							Request.QueryString["CampaignId"],
							userId,
							Security.EncryptPassword(Request.QueryString["SiteId"] + "-" + Request.QueryString["CampaignId"] + "-" + userId + "-" + HttpRuntime.Cache[Request.QueryString["Sign"]].ToString()),
							Request.QueryString["Sign"],
							Request.QueryString["TotalQuestionOnPage"]));
			}
			catch (Exception ex)
			{
				msg.Text = ex.Message;
#if DEBUG
				msg.Text = ex.ToString().Replace("\r\n", "<br/>");
#endif
			}
		}

		bool IsValidInput()
		{
			bool result = true;

			try
			{
				var temp = Convert.ToInt32(AgeInput.Text);
				if (temp < 20 || temp > 80)
				{
					msg.Text = "Tuổi không hợp lệ";
					result = false;
				}
			}
			catch (Exception ex)
			{
				msg.Text = "Tuổi không hợp lệ";
				result = false;
			}

			if (result)
				if (LevelOfEducationInput.Text.Trim().Length<2)
				{
					result = false;
					msg.Text = "Trình độ giáo dục phổ thông không hợp lệ";
				}
			return result;
		}
	}
}